﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using DevExpress.Utils.Menu;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Grid;
using ERP_RORZE_DLL.Product;
using ERP_RORZE_PERMISSION.Base;
using ERP_RORZE_PRODUCT.Product.BusOder;
using ERP_RORZE_DLL.Product.database;
using System.Data.SqlClient;
using ERP_RORZE_DLL;
using ERP_RORZE_SYSTEM;
using System.Data.OleDb;
using System.Data.Common;
using ERP_RORZE_DLL.Product.Base;
using DevExpress.XtraEditors.Repository;
using BaseDAO = ERP_RORZE_TOOL.DBAccess.BaseDAO;
using Utilities = ERP_RORZE_TOOL.Common.Utilities;

namespace ERP_RORZE_PRODUCT.Product.UserControls
{
    public partial class ctrlBusOderList : DevExpress.XtraEditors.XtraUserControl
    {
        private INISettings mySetting;
        private SqlConnection myConnection;
        private SqlConnection masterConnection;
        DXPopupMenu menu;
        private int range = 1;
        //
        ClsBusOderDAO clsBusOderDAO = new ClsBusOderDAO();
        DataTable dt;
        ClsBusOderTable busoder = new ClsBusOderTable();
        private LogUtils log;

        public ctrlBusOderList()
        {
            InitializeComponent();
            this.mySetting = new INISettings();
            this.myConnection = new SqlConnection(mySetting.SQLConnectionString);
            this.masterConnection = new SqlConnection(mySetting.DB2ConnectionString);

            InitDateRangeMenu();
            this.dropbtDateRange.DropDownControl = menu;
            this.dropbtDateRange.Text = "One Month";
            log = new LogUtils();
        }
        void Re_load(object sender, EventArgs e)
        {
            //dt = clsBusOderDAO.GetAll();
            //dgvBusOderList.DataSource = dt;
            //gridViewBusOder.BestFitColumns();

            BindDatatoGrid(range);

            //RepositoryItemTextEdit ri = new RepositoryItemTextEdit();
            //DevExpress.XtraGrid.Columns.GridColumn col = gridViewBusOder.Columns["Imported"];
            //col.ColumnEdit = ri;
            //col.OptionsColumn.AllowEdit = false;
            //ri.CustomDisplayText += new DevExpress.XtraEditors.Controls.CustomDisplayTextEventHandler(ri_CustomDisplayText);

            //RepositoryItemTextEdit ri1 = new RepositoryItemTextEdit();
            //DevExpress.XtraGrid.Columns.GridColumn col1 = gridViewBusOder.Columns["Started"];
            //col1.ColumnEdit = ri1;
            //col1.OptionsColumn.AllowEdit = false;
            //ri1.CustomDisplayText += new DevExpress.XtraEditors.Controls.CustomDisplayTextEventHandler(ri_CustomDisplayText);

            //RepositoryItemTextEdit ri2 = new RepositoryItemTextEdit();
            //DevExpress.XtraGrid.Columns.GridColumn col2 = gridViewBusOder.Columns["Finished"];
            //col2.ColumnEdit = ri2;
            //col2.OptionsColumn.AllowEdit = false;
            //ri1.CustomDisplayText += new DevExpress.XtraEditors.Controls.CustomDisplayTextEventHandler(ri_CustomDisplayText);

        }
        private void ctrlBusOderList_Load(object sender, EventArgs e)
        {
            Re_load(sender, e);
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Bạn có thực sự muốn xóa dữ liệu!", "Message", MessageBoxButtons.OKCancel,
                                MessageBoxIcon.Question) == DialogResult.OK)
            {
                busoder.BOderNo =
                    gridViewBusOder.GetRowCellValue(gridViewBusOder.FocusedRowHandle, "BOderNo").ToString();
                clsBusOderDAO.Delete(busoder);

                //write Log
                log.Table = LogConstant.Table.Product.BusOrderList;
                log.Task = LogConstant.Task.Delete;
                log.Description = "BOrderNo: " + busoder.BOderNo;
                log.WriteLog();

            }
            Re_load(sender, e);
        }

        private void btnReload_Click(object sender, EventArgs e)
        {
            Re_load(sender, e);
        }

        private void btnAddNew_Click(object sender, EventArgs e)
        {
            Frm_BusOderAdd frmAdd = new Frm_BusOderAdd();
            frmAdd.Re_Load += new EventHandler(Re_load);
            frmAdd.Show();
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            try
            {
                Frm_BusOderEdit frmEdit = new Frm_BusOderEdit();
                frmEdit.Re_Load += new EventHandler(Re_load);
                frmEdit.BOderNo = gridViewBusOder.GetRowCellValue(gridViewBusOder.FocusedRowHandle, "BOderNo").ToString();
                frmEdit.BlastQty = gridViewBusOder.GetRowCellValue(gridViewBusOder.FocusedRowHandle, "BlastQty").ToString();
                frmEdit.Change = gridViewBusOder.GetRowCellValue(gridViewBusOder.FocusedRowHandle, "Change").ToString();
                frmEdit.ChangeDate = gridViewBusOder.GetRowCellValue(gridViewBusOder.FocusedRowHandle, "ChangeDate").ToString();
                frmEdit.date = gridViewBusOder.GetRowCellValue(gridViewBusOder.FocusedRowHandle, "date").ToString();
                frmEdit.Dealine = gridViewBusOder.GetRowCellValue(gridViewBusOder.FocusedRowHandle, "Deadline").ToString();
                frmEdit.Finished = gridViewBusOder.GetRowCellValue(gridViewBusOder.FocusedRowHandle, "Finished").ToString();
                frmEdit.FinishDate = gridViewBusOder.GetRowCellValue(gridViewBusOder.FocusedRowHandle, "FinishDate").ToString();
                frmEdit.HelisertQty = gridViewBusOder.GetRowCellValue(gridViewBusOder.FocusedRowHandle, "HelisertQty").ToString();
                frmEdit.Imported = gridViewBusOder.GetRowCellValue(gridViewBusOder.FocusedRowHandle, "Imported").ToString();
                frmEdit.ImportFrom = gridViewBusOder.GetRowCellValue(gridViewBusOder.FocusedRowHandle, "ImportFrom").ToString();
                //frmEdit.MONo = gridViewBusOder.GetRowCellValue(gridViewBusOder.FocusedRowHandle, "MONo").ToString();
                frmEdit.MOQty = gridViewBusOder.GetRowCellValue(gridViewBusOder.FocusedRowHandle, "MOQty").ToString();
                frmEdit.Note = gridViewBusOder.GetRowCellValue(gridViewBusOder.FocusedRowHandle, "Note").ToString();
                frmEdit.PartID = gridViewBusOder.GetRowCellValue(gridViewBusOder.FocusedRowHandle, "PartID").ToString();
                frmEdit.planNo = gridViewBusOder.GetRowCellValue(gridViewBusOder.FocusedRowHandle, "planNo").ToString();
                frmEdit.Qty = gridViewBusOder.GetRowCellValue(gridViewBusOder.FocusedRowHandle, "Qty").ToString();
                frmEdit.RawQty = gridViewBusOder.GetRowCellValue(gridViewBusOder.FocusedRowHandle, "RawQty").ToString();
                frmEdit.Started = gridViewBusOder.GetRowCellValue(gridViewBusOder.FocusedRowHandle, "Started").ToString();
                frmEdit.Show();
            }
            catch
            {
            }
        }

        private void btnImport_Click(object sender, EventArgs e)
        {
            //FileDialog fileDialog = new OpenFileDialog();
            //fileDialog.Filter = "Excel 2007-2013|*.xlsx|Excel 97-2003 (*.xls)|*.xls";
            //if (fileDialog.Show() == DialogResult.OK)
            //{
            //    OleDbConnection connection = new OleDbConnection();
            //    try
            //    {
            //        string path = fileDialog.FileName;
            //        INISettings iniSettings = new INISettings();
            //        string connectString = iniSettings.SQLConnectionString;
            //        // Connection String to Excel Workbook
            //        string excelConnectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 12.0;Persist Security Info=False", path);

            //        connection.ConnectionString = excelConnectionString;
            //        OleDbCommand command = new OleDbCommand("select * from [Sheet1$]", connection);
            //        connection.Open();
            //        // Create DbDataReader to Data Worksheet
            //        DbDataReader dr = command.ExecuteReader();

            //        // Bulk Copy to SQL Server 
            //        SqlBulkCopy bulkInsert = new SqlBulkCopy(connectString);
            //        bulkInsert.DestinationTableName = "[rrc_database].[dbo].[242_BusOder]";

            //        SqlBulkCopyColumnMapping date = new SqlBulkCopyColumnMapping("BOderNo", "BOderNo");
            //        bulkInsert.ColumnMappings.Add(date);

            //        SqlBulkCopyColumnMapping toolId = new SqlBulkCopyColumnMapping("date", "date");
            //        bulkInsert.ColumnMappings.Add(toolId);

            //        SqlBulkCopyColumnMapping makerId = new SqlBulkCopyColumnMapping("planNo", "planNo");
            //        bulkInsert.ColumnMappings.Add(makerId);

            //        SqlBulkCopyColumnMapping PartID = new SqlBulkCopyColumnMapping("PartID", "PartID");
            //        bulkInsert.ColumnMappings.Add(PartID);

            //        SqlBulkCopyColumnMapping Qty = new SqlBulkCopyColumnMapping("Qty", "Qty");
            //        bulkInsert.ColumnMappings.Add(Qty);

            //        SqlBulkCopyColumnMapping Deadline = new SqlBulkCopyColumnMapping("Deadline", "Deadline");
            //        bulkInsert.ColumnMappings.Add(Deadline);

            //        SqlBulkCopyColumnMapping RawQty = new SqlBulkCopyColumnMapping("RawQty", "RawQty");
            //        bulkInsert.ColumnMappings.Add(RawQty);

            //        SqlBulkCopyColumnMapping HelisertQty = new SqlBulkCopyColumnMapping("HelisertQty", "HelisertQty");
            //        bulkInsert.ColumnMappings.Add(HelisertQty);

            //        SqlBulkCopyColumnMapping BlastQty = new SqlBulkCopyColumnMapping("BlastQty", "BlastQty");
            //        bulkInsert.ColumnMappings.Add(BlastQty);

            //        SqlBulkCopyColumnMapping MONo = new SqlBulkCopyColumnMapping("MONo", "MONo");
            //        bulkInsert.ColumnMappings.Add(MONo);

            //        SqlBulkCopyColumnMapping MOQty = new SqlBulkCopyColumnMapping("MOQty", "MOQty");
            //        bulkInsert.ColumnMappings.Add(MOQty);

            //        SqlBulkCopyColumnMapping Started = new SqlBulkCopyColumnMapping("Started", "Started");
            //        bulkInsert.ColumnMappings.Add(Started);

            //        SqlBulkCopyColumnMapping Finished = new SqlBulkCopyColumnMapping("Finished", "Finished");
            //        bulkInsert.ColumnMappings.Add(Finished);

            //        SqlBulkCopyColumnMapping FinishDate = new SqlBulkCopyColumnMapping("FinishDate", "FinishDate");
            //        bulkInsert.ColumnMappings.Add(FinishDate);

            //        SqlBulkCopyColumnMapping Change = new SqlBulkCopyColumnMapping("Change", "Change");
            //        bulkInsert.ColumnMappings.Add(Change);

            //        SqlBulkCopyColumnMapping ChangeDate = new SqlBulkCopyColumnMapping("ChangeDate", "ChangeDate");
            //        bulkInsert.ColumnMappings.Add(ChangeDate);

            //        SqlBulkCopyColumnMapping Imported = new SqlBulkCopyColumnMapping("Imported", "Imported");
            //        bulkInsert.ColumnMappings.Add(Imported);

            //        SqlBulkCopyColumnMapping ImportFrom = new SqlBulkCopyColumnMapping("ImportFrom", "ImportFrom");
            //        bulkInsert.ColumnMappings.Add(ImportFrom);

            //        SqlBulkCopyColumnMapping Note = new SqlBulkCopyColumnMapping("Note", "Note");
            //        bulkInsert.ColumnMappings.Add(Note);

            //        bulkInsert.WriteToServer(dr);

            //        connection.Close();
            //        Re_load(sender, e);
            //    }
            //    catch (Exception ex)
            //    {
            //        MessageBox.Show(ex.Message);
            //        connection.Close();
            //    }
            //}

            ImportData();
        }

        private void ImportData()
        {
            INISettings mySetting = new INISettings();
            SqlConnection myConnection = new SqlConnection(mySetting.SQLConnectionString);

            int countOk = 0;
            int countDup = 0;
            int countErr = 0;

            List<Utilities.ListItem> listDup = new List<Utilities.ListItem>();
            List<Utilities.ListItem> listErr = new List<Utilities.ListItem>();

            FileDialog importFile = new OpenFileDialog();
            importFile.Filter = "Excel 2007-2013|*.xlsx|Excel 97-2003 (*.xls)|*.xls";
            if (importFile.ShowDialog() == DialogResult.OK)
            {
                OleDbConnection excelConnection = null;
                try
                {
                    Control parent = progressPanel1.Parent;
                    progressPanel1.Location =
                        new Point(parent.Bounds.X + parent.Bounds.Width / 2 - progressPanel1.Width / 2,
                                  parent.Bounds.Y + parent.Bounds.Height / 2 - progressPanel1.Height / 2);
                    progressPanel1.Visible = true;
                    string excelConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
                                                   importFile.FileName +
                                                   ";Extended Properties=Excel 12.0;Persist Security Info=False";
                    excelConnection = new OleDbConnection(excelConnectionString);
                    OleDbCommand cmd =
                        new OleDbCommand("select [BOrderNo],[Date],[PlanNo],[PartNo],[Qty],[Deadline]" +
                                         ",[RawQty],[HelisertQty],[BlastQty],[MONo],[MOQty]" +
                                         ",[Started],[Finished],[FinishDate],[Change],[ChangeDate]" +
                                         ",[Imported],[ImportFrom],[Note] from [Sheet1$]",
                                         excelConnection);
                    excelConnection.Open();
                    OleDbDataReader dReader;
                    dReader = cmd.ExecuteReader();


                    int line = 1;
                    string lineDup = string.Empty;

                    string BOrderNo = string.Empty;
                    string Date = string.Empty;
                    string PlanNo = string.Empty;
                    string PartID = string.Empty;
                    string Qty = string.Empty;
                    string Deadline = string.Empty;
                    string RawQty = string.Empty;
                    string HelisertQty = string.Empty;
                    string BlastQty = string.Empty;
                    string MONo = string.Empty;
                    string MOQty = string.Empty;
                    string Started = string.Empty;
                    string Finished = string.Empty;
                    string FinishDate = string.Empty;
                    string Change = string.Empty;
                    string ChangeDate = string.Empty;
                    string Imported = string.Empty;
                    string ImportFrom = string.Empty;
                    string Note = string.Empty;


                    myConnection.Open();
                    while (dReader.Read())
                    {
                        bool exist = false;
                        line++;
                        try
                        {
                            string dt = dReader["Date"].ToString().Trim();
                            if (dReader["BOrderNo"].ToString().Trim().Equals(string.Empty)
                                && dReader["Date"].ToString().Trim().Equals(string.Empty)
                                && dReader["PlanNo"].ToString().Trim().Equals(string.Empty)
                                && dReader["PartNo"].ToString().Trim().Equals(string.Empty)
                                && dReader["Qty"].ToString().Trim().Equals(string.Empty)
                                && dReader["Deadline"].ToString().Trim().Equals(string.Empty)
                                && dReader["RawQty"].ToString().Trim().Equals(string.Empty)
                                && dReader["HelisertQty"].ToString().Trim().Equals(string.Empty)
                                && dReader["BlastQty"].ToString().Trim().Equals(string.Empty)
                                && dReader["MONo"].ToString().Trim().Equals(string.Empty)
                                && dReader["MOQty"].ToString().Trim().Equals(string.Empty)
                                && dReader["Started"].ToString().Trim().Equals(string.Empty)
                                && dReader["Finished"].ToString().Trim().Equals(string.Empty)
                                && dReader["FinishDate"].ToString().Trim().Equals(string.Empty)
                                && dReader["Change"].ToString().Trim().Equals(string.Empty)
                                && dReader["ChangeDate"].ToString().Trim().Equals(string.Empty)
                                && dReader["Imported"].ToString().Trim().Equals(string.Empty)
                                && dReader["ImportFrom"].ToString().Trim().Equals(string.Empty)
                                && dReader["Note"].ToString().Trim().Equals(string.Empty)
                                )
                            {
                                countErr++;
                                listErr.Add(new Utilities.ListItem(line.ToString(), dReader["BOrderNo"].ToString(), "Null line"));
                                exist = true;
                            }
                        }
                        catch (Exception e)
                        {
                            countErr++;
                            listErr.Add(new Utilities.ListItem(line.ToString(), dReader["BOrderNo"].ToString(), e.Message));
                            exist = true;
                        }

                        if (!exist)
                        {
                            try
                            {
                                SqlCommand cmd_sql = myConnection.CreateCommand();
                                cmd_sql.CommandText = "SELECT * FROM [242_BusOder] WHERE [BOderNo]='" +
                                                      dReader["BOrderNo"].ToString() + "'";
                                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                                if (dataReader.Read())
                                {

                                    exist = true;
                                    countDup++;
                                    listDup.Add(new Utilities.ListItem(line.ToString(), dReader["BOrderNo"].ToString(),
                                                                       "Duplicate"));

                                    // lineDup += line.ToString() + ", ";
                                }
                                dataReader.Close();
                                cmd_sql.Dispose();
                            }
                            catch (Exception e)
                            {
                                countErr++;
                                listErr.Add(new Utilities.ListItem(line.ToString(), dReader["BOrderNo"].ToString(),
                                                                   e.Message));
                                exist = true;
                            }
                        }

                        if (!exist)
                        {
                            try
                            {
                                BOrderNo = (dReader["BOrderNo"].ToString().Equals(string.Empty)) ? "null" : "'" + dReader["BOrderNo"].ToString() + "'";
                                Date = (dReader["Date"].ToString().Equals(string.Empty)) ? "null" : "'" + DateTime.Parse(dReader["Date"].ToString()).ToShortDateString() + "'";
                                PlanNo = (dReader["PlanNo"].ToString().Equals(string.Empty)) ? "null" : "'" + (dReader["PlanNo"].ToString()) + "'";
                                PartID = (dReader["PartNo"].ToString().Trim().Equals(string.Empty)) ? "null" : "N'" + dReader["PartNo"].ToString().Trim() + "'";
                                Qty = (dReader["Qty"].ToString().Equals(string.Empty)) ? "null" : dReader["Qty"].ToString();
                                Deadline = (dReader["Deadline"].ToString().Equals(string.Empty)) ? "null" : "'" + DateTime.Parse(dReader["Deadline"].ToString()).ToShortDateString() + "'";
                                RawQty = (dReader["RawQty"].ToString().Equals(string.Empty)) ? "null" : dReader["RawQty"].ToString();
                                HelisertQty = (dReader["HelisertQty"].ToString().Equals(string.Empty)) ? "null" : dReader["HelisertQty"].ToString();
                                BlastQty = (dReader["BlastQty"].ToString().Equals(string.Empty)) ? "null" : dReader["BlastQty"].ToString();
                                MONo = (dReader["MONo"].ToString().Equals(string.Empty)) ? "null" : "'" + dReader["MONo"].ToString() + "'";
                                MOQty = (dReader["MOQty"].ToString().Equals(string.Empty)) ? "null" : dReader["MOQty"].ToString();
                                Started = (dReader["Started"].ToString().Equals(string.Empty)) ? "null" : "'" + dReader["Started"].ToString() + "'";
                                Finished = (dReader["Finished"].ToString().Equals(string.Empty)) ? "null" : "'" + dReader["Finished"].ToString() + "'";
                                FinishDate = (dReader["FinishDate"].ToString().Equals(string.Empty)) ? "null" : "'" + DateTime.Parse(dReader["FinishDate"].ToString()).ToShortDateString() + "'";
                                Change = (dReader["Change"].ToString().Equals(string.Empty)) ? "null" : "N'" + dReader["Change"].ToString() + "'";
                                ChangeDate = (dReader["ChangeDate"].ToString().Equals(string.Empty)) ? "null" : "N'" + DateTime.Parse(dReader["ChangeDate"].ToString()).ToShortDateString() + "'";
                                Imported = (dReader["Imported"].ToString().Equals(string.Empty)) ? "null" : "'" + dReader["Imported"].ToString() + "'";
                                ImportFrom = (dReader["ImportFrom"].ToString().Equals(string.Empty)) ? "null" : "N'" + dReader["ImportFrom"].ToString() + "'";
                                Note = (dReader["Note"].ToString().Equals(string.Empty)) ? "null" : "N'" + dReader["Note"].ToString() + "'";
                            }
                            catch (Exception ex)
                            {
                                countErr++;
                                listErr.Add(new Utilities.ListItem(line.ToString(), dReader["BOrderNo"].ToString(), ex.Message));
                                exist = true;

                            }
                        }

                        if (!exist)
                        {
                            try
                            {
                                string sql = "INSERT INTO [242_BusOder] ([BOderNo],[date],[planNo],[PartID]" +
                                         ",[Qty],[Deadline],[RawQty],[HelisertQty],[BlastQty],[MONo],[MOQty]" +
                                         ",[Started],[Finished],[FinishDate],[Change],[ChangeDate],[Imported]" +
                                         ",[ImportFrom],[Note])"
                                         + " VALUES (" + BOrderNo + ", " + Date + ", " + PlanNo + ","
                                         + PartID + "," + Qty + ", " + Deadline + ", " + RawQty + ", " + HelisertQty + ", "
                                         + BlastQty + " ," + MONo + ", " + MOQty + ", " + Started + ", " + Finished + ", " + FinishDate + ", "
                                         + Change + ", " + ChangeDate + ", " + Imported + ", " + ImportFrom + ", " + Note + ")";
                                SqlCommand cmd_sql = new SqlCommand(sql, myConnection);

                                cmd_sql.ExecuteNonQuery();
                                cmd_sql.Dispose();
                                countOk++;

                            }
                            catch (Exception ex)
                            {
                                countErr++;
                                listErr.Add(new Utilities.ListItem(line.ToString(), dReader["BOrderNo"].ToString(), ex.Message));

                            }
                        }
                    }
                    myConnection.Close();
                    progressPanel1.Visible = false;
                    excelConnection.Close();
                    //MessageBox.Show(countOk + " records have been imported. \n" + countDup.ToString() + " record(s) duplicated (Lines: " + lineDup + ")");
                    //LoadData();

                    //write Log
                    log.Table = LogConstant.Table.Product.BusOrderList;
                    log.Task = LogConstant.Task.Import;
                    log.Description = string.Format(LogConstant.Message.Import, countOk.ToString(), "");
                    log.WriteLog();

                    Frm_ImportReport report = new Frm_ImportReport(countOk, listDup, listErr, "BusOrder");
                    report.StartPosition = FormStartPosition.CenterScreen;
                    report.Show();
                    report.Activate();
                }
                catch (Exception ex)
                {
                    if (excelConnection.State == ConnectionState.Open)
                    {
                        excelConnection.Close();
                    }
                    if (myConnection.State == ConnectionState.Open)
                    {
                        myConnection.Close();
                    }
                    progressPanel1.Visible = false;
                    MessageBox.Show(ex.Message);
                }


            }
        }


        private void btnRefresh_Click(object sender, EventArgs e)
        {
            Re_load(sender, e);
        }

        private void simpleButton1_Click(object sender, EventArgs e)
        {
            btnImport_Click(sender, e);
        }

        private void btEdit_Click(object sender, EventArgs e)
        {
            btnEdit_Click(sender, e);
        }

        private void btDelete_Click(object sender, EventArgs e)
        {
            btnDelete_Click(sender, e);
        }

        private void btnBusOderCancel_Click(object sender, EventArgs e)
        {
            CtrlBusOderCancel frmAdd = new CtrlBusOderCancel();
            frmAdd.Reload += new EventHandler(Re_load);
            frmAdd.Show();
        }

        private void btnBusOderDeadline_Click(object sender, EventArgs e)
        {
            ctrlBusOderDeadline frmObj = new ctrlBusOderDeadline();
            frmObj.Reload += new EventHandler(Re_load);
            frmObj.Show();
        }

        private void btnBusOderQtyChange_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            ctrlBusOderQtyChange frmObj = new ctrlBusOderQtyChange();
            frmObj.Reload += new EventHandler(Re_load);
            frmObj.Show();
            Cursor.Current = Cursors.Default;
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            Frm_BusOderAdd frmAdd = new Frm_BusOderAdd();
            frmAdd.Re_Load += new EventHandler(Re_load);
            frmAdd.Show();
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            clsConstantsFuction.ExportToExcel(gridViewBusOder, 1, true);
        }
        void ri_CustomDisplayText(object sender, DevExpress.XtraEditors.Controls.CustomDisplayTextEventArgs e)
        {
            e.DisplayText = true.Equals(e.Value) ? "True" : "False";
        }

        //Date range
        protected virtual void InitDateRangeMenu()
        {
            menu = new DXPopupMenu();
            menu.Items.Add(new DXMenuItem("One Month", new EventHandler(OnItemClick1Month), null, null, null, null));
            menu.Items.Add(new DXMenuItem("3 Months", new EventHandler(OnItemClick3Month), null, null, null, null));
            menu.Items.Add(new DXMenuItem("6 Months", new EventHandler(OnItemClick6Months), null, null, null, null));
            menu.Items.Add(new DXMenuItem("One Year", new EventHandler(OnItemClick1Year), null, null, null, null));
            menu.Items.Add(new DXMenuItem("All time", new EventHandler(OnItemClickAllTime), null, null, null, null));

        }

        void OnItemClick1Month(object sender, EventArgs e)
        {
            BindDatatoGrid(1);
            range = 1;
            dropbtDateRange.Text = "One Month";
        }

        void OnItemClick3Month(object sender, EventArgs e)
        {
            BindDatatoGrid(2);
            range = 2;
            dropbtDateRange.Text = "3 Months";
        }

        void OnItemClick6Months(object sender, EventArgs e)
        {
            BindDatatoGrid(3);
            range = 3;
            dropbtDateRange.Text = "6 Months";
        }

        void OnItemClick1Year(object sender, EventArgs e)
        {
            BindDatatoGrid(4);
            range = 4;
            dropbtDateRange.Text = "One Year";
        }

        void OnItemClickAllTime(object sender, EventArgs e)
        {
            BindDatatoGrid(0);
            range = 0;
            dropbtDateRange.Text = "All time";
        }

        private void BindDatatoGrid(int range = 1)
        {
            Cursor.Current = Cursors.WaitCursor;
            // gridViewBusOder.Columns.Clear();
            dt = clsBusOderDAO.GetAllRange(range);
            dgvBusOderList.DataSource = dt;
            gridViewBusOder.BestFitColumns();
            Cursor.Current = Cursors.Default;

        }

        private void btnRefresh_Click_1(object sender, EventArgs e)
        {
            BindDatatoGrid(range);
        }

        private void gridViewBusOder_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            GridView view = sender as GridView;

            //Kiểm tra đây là dòng dữ liệu mới hay cũ, nếu là mới thì mình insert
            if (view.IsNewItemRow(e.RowHandle))
            {
                //e.RowHandle trả về giá trị int là thứ tự của dòng hiện tại

            }
            //Cũ thì update
            else
            {
                string temDate = (view.GetRowCellValue(e.RowHandle, view.Columns["FinishDate"]).ToString().Trim() != string.Empty) ? DateTime.Parse(view.GetRowCellValue(e.RowHandle, view.Columns["FinishDate"]).ToString()).ToString("yyyy/MM/dd") : view.GetRowCellValue(e.RowHandle, view.Columns["FinishDate"]).ToString().Trim();

                string Finishdate = (temDate == "0001/01/01" || temDate == "") ? "null" : "'" + DateTime.Parse(view.GetRowCellValue(e.RowHandle, view.Columns["FinishDate"]).ToString()).ToString("yyyy/MM/dd") + "'";

                string Finished = (view.GetRowCellValue(e.RowHandle, view.Columns["Finished"]).ToString() == "") ? "null" : "'" + view.GetRowCellValue(e.RowHandle, view.Columns["Finished"]).ToString() + "'";
                string PartID = (view.GetRowCellValue(e.RowHandle, view.Columns["PartID"]).ToString() == "") ? "null" : "'" + view.GetRowCellValue(e.RowHandle, view.Columns["PartID"]).ToString() + "'";
                string Note = (view.GetRowCellValue(e.RowHandle, view.Columns["Note"]).ToString() == "") ? "null" : "N'" + view.GetRowCellValue(e.RowHandle, view.Columns["Note"]).ToString() + "'";
                string BOderNo = (view.GetRowCellValue(e.RowHandle, view.Columns["BOderNo"]).ToString() == "") ? "null" : "'" + view.GetRowCellValue(e.RowHandle, view.Columns["BOderNo"]).ToString() + "'";
                string MOQty = (view.GetRowCellValue(e.RowHandle, view.Columns["MOQty"]).ToString() == "") ? "null" : view.GetRowCellValue(e.RowHandle, view.Columns["MOQty"]).ToString();
                string HelisertQty = (view.GetRowCellValue(e.RowHandle, view.Columns["HelisertQty"]).ToString() == "") ? "null" : view.GetRowCellValue(e.RowHandle, view.Columns["HelisertQty"]).ToString();
                string BlastQty = (view.GetRowCellValue(e.RowHandle, view.Columns["BlastQty"]).ToString() == "") ? "null" : view.GetRowCellValue(e.RowHandle, view.Columns["BlastQty"]).ToString();

                string update = "update [242_BusOder] set [Finished]=" + Finished
                    + ", [FinishDate] = " + Finishdate
                    + ", [PartID] = " + PartID
                    + ", [Note] = " + Note
                    + ", [MOQty] = " + MOQty
                    + ", [BlastQty] = " + BlastQty
                    + ", [HelisertQty] = " + HelisertQty
                    + " where [BOderNo] = " + BOderNo;
                if (BaseDAO.ExecuteNonQuery(update) > 0)
                {
                    //write Log
                    log.Table = LogConstant.Table.Product.BusOrderList;
                    log.Task = LogConstant.Task.Update;
                    log.Description = "Finished:" + Finished + "; FinishDate:" + Finishdate + "; PartID:" + PartID + "; Note:" + Note + "; MOQty:" + MOQty + " where BOrderNo:" + BOderNo;
                    log.WriteLog();

                }

            }
        }

        private void gridViewBusOder_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Alt)
            {
                if (e.KeyCode == Keys.E)
                {
                    if (gridViewBusOder.OptionsBehavior.Editable)
                    {
                        gridViewBusOder.OptionsBehavior.Editable = false;
                    }
                    else
                    {
                        gridViewBusOder.OptionsBehavior.Editable = true;
                        foreach (GridColumn column in gridViewBusOder.Columns)
                        {
                            if (!column.FieldName.Equals("PartID") && !column.FieldName.Equals("Finished") && !column.FieldName.Equals("FinishDate") && !column.FieldName.Equals("Note") && !column.FieldName.Equals("MOQty") && !column.FieldName.Equals("BlastQty") && !column.FieldName.Equals("HelisertQty"))
                            {
                                column.OptionsColumn.AllowEdit = false;
                            }
                        }
                    }
                }
            }
        }
    }
}
